package store.lunangangster.nodeflow.rt.element.flow;

import static store.lunangangster.nodeflow.enums.FlowType.FLOW_WHILE;

import cn.hutool.core.collection.CollUtil;
import store.lunangangster.nodeflow.core.component.NodeComponent;
import store.lunangangster.nodeflow.enums.FlowType;
import store.lunangangster.nodeflow.rt.DataBus;
import store.lunangangster.nodeflow.rt.element.Node;

/**
 * While循环执行流
 *
 * @author cwk
 * @version 1.0
 */
public class WhileFlow extends LoopFlow {

  private Node whileNode;

  @Override
  public void execute(Integer slotIndex) {
    while (execute0(slotIndex)) {
      doWhile(slotIndex);
      if (exit(slotIndex)) {
        break;
      }
    }
  }

  private boolean execute0(Integer slotIndex) {
    NodeComponent whileComp = whileNode.getNodeComponent();
    try {
      whileNode.execute(slotIndex);
      return (boolean) DataBus.getSlot(slotIndex).getData(whileComp.getWhileEnterKey());
    } finally {
      whileComp.removeWhileEnterKey();
    }
  }

  private void doWhile(Integer slotIndex) {
    if (CollUtil.isEmpty(this.executableList)) {
      return;
    }
    executableList.forEach(executable -> executable.execute(slotIndex));
  }

  @Override
  public FlowType getFlowType() {
    return FLOW_WHILE;
  }

  public Node getWhileNode() {
    return whileNode;
  }

  public void setWhileNode(Node whileNode) {
    this.whileNode = whileNode;
  }
}
